<template>
  <div class="user-management">
    <div class="page-header">
      <div class="header-left">
        <el-button type="primary" @click="$router.push('/')">
          <el-icon><ArrowLeft /></el-icon>
          返回主页
        </el-button>
      </div>
      <div class="header-center">
        <h2>用户管理</h2>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="userList"
      style="width: 100%"
      border
    >
      <el-table-column prop="userId" label="用户ID" width="80" />
      <el-table-column label="头像" width="70">
        <template #default="scope">
          <el-avatar
            :size="40"
            :src="scope.row.imageUrl || 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'"
          />
        </template>
      </el-table-column>
      <el-table-column prop="userName" label="用户名" width="120" />
      <el-table-column prop="callName" label="昵称" width="120" />
      <el-table-column prop="phoneNumber" label="手机号" width="120" />
      <el-table-column prop="bio" label="个人简介" min-width="150">
        <template #default="scope">
          {{ scope.row.bio || '暂无简介' }}
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="注册时间" width="180">
        <template #default="scope">
          {{ formatDate(scope.row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column prop="roles" label="用户角色" width="120">
        <template #default="scope">
          <el-tag
            :type="getUserRoleType(scope.row.userRoles)"
          >
            {{ getUserRoleLabel(scope.row.userRoles) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="320">
        <template #default="scope">
          <el-button
            :type="scope.row.status === 1 ? 'danger' : 'success'"
            size="small"
            @click="handleStatusChange(scope.row)"
          >
            {{ scope.row.status === 1 ? '禁用' : '启用' }}
          </el-button>
          <el-button
            type="primary"
            size="small"
            @click="handleEdit(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            type="warning"
            size="small"
            @click="handleResetPassword(scope.row)"
          >
            重置密码
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[10, 20, 50, 100]"
      :total="total"
      layout="total, sizes, prev, pager, next"
      class="pagination"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <!-- 编辑用户对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑用户信息"
      width="500px"
    >
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="editForm.username" disabled />
        </el-form-item>
        <el-form-item label="昵称">
          <el-input v-model="editForm.callName" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="个人简介">
          <el-input
            v-model="editForm.bio"
            type="textarea"
            :rows="3"
            placeholder="请输入个人简介"
          />
        </el-form-item>
        <el-form-item label="用户角色">
          <el-checkbox-group v-model="editForm.roles">
            <el-checkbox label="1">管理员</el-checkbox>
            <el-checkbox label="2">普通用户</el-checkbox>
            <el-checkbox label="3">专家</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEdit">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh, ArrowLeft } from '@element-plus/icons-vue'
import { 
  getAllUsers, 
  updateUserStatus, 
  updateUserRoles, 
  updateUserInfo,
  resetUserPassword,
  deleteUser
} from '@/api/user'

const loading = ref(false)
const userList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const editDialogVisible = ref(false)
const editForm = ref({
  userId: null,
  username: '',
  callName: '',
  phone: '',
  bio: '',
  roles: []
})

// 格式化日期
const formatDate = (date) => {
  if (!date) return ''
  const d = new Date(date)
  return d.toLocaleString()
}

// 获取用户列表
const getUserList = async () => {
  loading.value = true
  try {
    const res = await getAllUsers({
      page: currentPage.value,
      pageSize: pageSize.value
    })
    console.log('获取到的用户列表原始数据:', res)
    
    // 处理MyBatis-Plus的分页响应格式
    if (res && res.records) {
      userList.value = res.records
      total.value = res.total || res.records.length
    } else if (res && Array.isArray(res)) {
      userList.value = res
      total.value = res.length
    } else {
      console.error('无效的数据格式:', res)
      userList.value = []
      total.value = 0
      ElMessage.warning('暂无用户数据')
    }
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
    userList.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refreshData = () => {
  getUserList()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  getUserList()
}

// 处理每页条数变化
const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  getUserList()
}

// 处理用户状态变更
const handleStatusChange = async (user) => {
  try {
    await ElMessageBox.confirm(
      `确定要${user.status === 1 ? '禁用' : '启用'}该用户吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await updateUserStatus({
      userId: user.userId,
      status: user.status === 1 ? 0 : 1
    })
    
    ElMessage.success('操作成功')
    getUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新用户状态失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

// 打开编辑对话框
const handleEdit = (user) => {
  editForm.value = {
    userId: user.userId,
    username: user.userName,
    callName: user.callName,
    phone: user.phoneNumber,
    bio: user.bio || '',
    roles: user.userRoles?.map(role => role.roleId.toString()) || []
  }
  editDialogVisible.value = true
}

// 提交编辑
const submitEdit = async () => {
  try {
    // 更新用户基本信息
    await updateUserInfo({
      userId: editForm.value.userId,
      phoneNumber: editForm.value.phone,
      callName: editForm.value.callName,
      bio: editForm.value.bio
    })
    
    // 更新用户角色
    await updateUserRoles({
      userId: editForm.value.userId,
      roleIds: editForm.value.roles.map(Number)
    })
    
    ElMessage.success('保存成功')
    editDialogVisible.value = false
    getUserList()
  } catch (error) {
    console.error('保存用户信息失败:', error)
    ElMessage.error('保存失败')
  }
}

// 处理重置密码
const handleResetPassword = async (user) => {
  try {
    await ElMessageBox.confirm(
      '确定要重置该用户的密码吗？重置后的密码为：123456',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await resetUserPassword(user.userId)
    
    ElMessage.success('密码重置成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('重置密码失败:', error)
      ElMessage.error('重置密码失败')
    }
  }
}

// 处理删除用户
const handleDelete = async (user) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该用户吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'danger'
      }
    )
    
    await deleteUser(user.userId)
    
    ElMessage.success('删除成功')
    getUserList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除用户失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取用户角色类型
const getUserRoleType = (userRoles) => {
  if (!userRoles || userRoles.length === 0) return 'info'
  
  // 检查是否是管理员
  const isAdmin = userRoles.some(role => role.roleId === 1 && role.applyType === 1)
  if (isAdmin) return 'danger'
  
  // 检查是否是专家
  const isExpert = userRoles.some(role => role.roleId === 3 && role.applyType === 1)
  if (isExpert) return 'success'
  
  // 其他情况为普通用户
  return 'info'
}

// 获取用户角色标签
const getUserRoleLabel = (userRoles) => {
  if (!userRoles || userRoles.length === 0) return '普通用户'
  
  // 检查是否是管理员
  const isAdmin = userRoles.some(role => role.roleId === 1 && role.applyType === 1)
  if (isAdmin) return '管理员'
  
  // 检查是否是专家
  const isExpert = userRoles.some(role => role.roleId === 3 && role.applyType === 1)
  if (isExpert) return '专家'
  
  // 其他情况为普通用户
  return '普通用户'
}

onMounted(() => {
  getUserList()
})
</script>

<style scoped>
.user-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px 0;
}

.header-left {
  flex: 1;
}

.header-center {
  flex: 2;
  text-align: center;
}

.header-center h2 {
  margin: 0;
  font-size: 24px;
  color: #409EFF;
}

.header-right {
  flex: 1;
  display: flex;
  justify-content: flex-end;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.mx-1 {
  margin: 0 4px;
}

.el-tag.el-tag--danger {
  margin-right: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 